<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>班级课表座位管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        /* 核心布局 */
        .container-fluid { height: 100vh; padding: 10px; }
        #left-panel { width: 250px; border-right: 1px solid #ddd; }
        #main-content { flex: 1; padding: 20px; }

        /* 学生池样式 */
        #student-pool { 
            height: 300px; 
            border: 2px dashed #ccc; 
            margin: 10px 0; 
            padding: 10px;
            overflow-y: auto;
        }
        .student-item {
            display: inline-flex;
            align-items: center;
            padding: 5px;
            margin: 3px;
            border-radius: 15px;
            cursor: move;
            font-size: 12px;
        }
        .male { background: #3498db; color: white; }
        .female { background: #e74c3c; color: white; }

        /* 座位图样式 */
        .seat-grid {
            display: grid;
            gap: 5px;
            margin: 20px 0;
        }
        .seat-cell {
            width: 60px;
            height: 60px;
            border: 1px solid #ddd;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
            background: #f9f9f9;
        }
        .seat-student {
            width: 50px;
            height: 50px;
            border-radius: 25px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            cursor: move;
        }

        /* 课表样式 */
        #schedule-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        #schedule-table th, #schedule-table td {
            border: 1px solid #ddd;
            text-align: center;
            height: 40px;
            position: relative;
        }
        .course-block {
            position: absolute;
            width: 90%;
            left: 5%;
            top: 5%;
            height: 90%;
            background: #3498db;
            color: white;
            border-radius: 4px;
            cursor: move;
            font-size: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        /* 工具栏 */
        .toolbar { margin-bottom: 20px; }
        .toolbar button { margin-right: 5px; }
    </style>
</head>
<body>
    <div class="container-fluid d-flex">
        <!-- 左侧面板 -->
        <div id="left-panel" class="p-3">
            <div class="toolbar">
                <select id="class-select" class="form-select form-select-sm mb-2">
                    <option value="">选择班级...</option>
                </select>
                <button class="btn btn-sm btn-primary" onclick="addClass()">添加班级</button>
                <button class="btn btn-sm btn-success" onclick="exportData()">导出数据</button>
            </div>

            <div class="mb-3">
                <label class="form-label">添加学生</label>
                <div class="input-group input-group-sm">
                    <input type="text" class="form-control" id="student-name" placeholder="姓名">
                    <select class="form-select" id="student-gender">
                        <option value="M">男生</option>
                        <option value="F">女生</option>
                    </select>
                    <button class="btn btn-outline-secondary" onclick="addStudent()">添加</button>
                </div>
            </div>

            <div>
                <label class="form-label">学生池</label>
                <div id="student-pool"></div>
            </div>
        </div>

        <!-- 主内容区 -->
        <div id="main-content">
            <div class="toolbar">
                <button class="btn btn-sm btn-info" onclick="showTab('seat')">座位图</button>
                <button class="btn btn-sm btn-info" onclick="showTab('schedule')">课程表</button>
                <div class="btn-group float-end">
                    <button class="btn btn-sm btn-secondary" onclick="saveData()">保存</button>
                    <button class="btn btn-sm btn-warning" onclick="resetData()">重置</button>
                </div>
            </div>

            <!-- 座位图 -->
            <div id="seat-tab" class="tab-content">
                <div class="mb-3">
                    <label class="form-label">座位布局</label>
                    <div class="input-group input-group-sm">
                        <input type="number" class="form-control" id="rows" value="6" min="1" max="10" style="width:80px">
                        <span class="input-group-text">行</span>
                        <input type="number" class="form-control" id="cols" value="8" min="1" max="15" style="width:80px">
                        <span class="input-group-text">列</span>
                        <button class="btn btn-outline-secondary" onclick="generateSeats()">生成</button>
                    </div>
                </div>
                <div id="seat-map" class="seat-grid"></div>
            </div>

            <!-- 课程表 -->
            <div id="schedule-tab" class="tab-content" style="display:none">
                <div class="mb-3">
                    <label class="form-label">课程管理</label>
                    <div class="input-group input-group-sm">
                        <input type="text" class="form-control" id="course-name" placeholder="课程名称">
                        <input type="color" class="form-control form-control-color" id="course-color" value="#3498db">
                        <button class="btn btn-outline-secondary" onclick="addCourse()">添加课程</button>
                    </div>
                </div>
                <table id="schedule-table">
                    <thead>
                        <tr>
                            <th>时间</th>
                            <th>周一</th>
                            <th>周二</th>
                            <th>周三</th>
                            <th>周四</th>
                            <th>周五</th>
                            <th>周六</th>
                            <th>周日</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- 时间行动态生成 -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script>
        // 应用状态
        let state = {
            currentClass: null,
            classes: {},
            courses: [],
            timeSlots: [
                { start: 8*60, end: 8*60+45, label: '第一节<br>8:00-8:45' },
                { start: 9*60, end: 9*60+45, label: '第二节<br>9:00-9:45' },
                { start: 10*60+15, end: 11*60, label: '第三节<br>10:15-11:00' },
                { start: 11*60+15, end: 12*60, label: '第四节<br>11:15-12:00' },
                { start: 14*60, end: 14*60+45, label: '第五节<br>14:00-14:45' },
                { start: 15*60+15, end: 16*60, label: '第六节<br>15:15-16:00' }
            ]
        };

        // 初始化
        document.addEventListener('DOMContentLoaded', () => {
            loadState();
            generateTimeSlots();
            showTab('seat');
            initDragDrop();
        });

        // 拖拽功能初始化
        function initDragDrop() {
            document.addEventListener('dragstart', e => {
                if(e.target.classList.contains('student-item')) {
                    e.dataTransfer.setData('text/plain', JSON.stringify({
                        type: 'student',
                        id: e.target.dataset.id
                    }));
                }
                if(e.target.classList.contains('course-block')) {
                    e.dataTransfer.setData('text/plain', JSON.stringify({
                        type: 'course',
                        id: e.target.dataset.id
                    }));
                }
            });

            document.addEventListener('dragover', e => {
                if(e.target.classList.contains('seat-cell') || e.target.classList.contains('schedule-cell')) {
                    e.preventDefault();
                }
            });

            document.addEventListener('drop', e => {
                e.preventDefault();
                if(!state.currentClass) return;
                
                const data = JSON.parse(e.dataTransfer.getData('text/plain'));
                if(e.target.classList.contains('seat-cell')) {
                    const student = state.currentClass.students.find(s => s.id === data.id);
                    if(student) {
                        e.target.innerHTML = '';
                        const el = createStudentElement(student);
                        e.target.appendChild(el);
                        student.seat = { row: e.target.dataset.row, col: e.target.dataset.col };
                    }
                }
                if(e.target.classList.contains('schedule-cell')) {
                    const course = state.courses.find(c => c.id === data.id);
                    if(course) {
                        const day = parseInt(e.target.dataset.day);
                        const period = parseInt(e.target.dataset.period);
                        course.timeSlots = course.timeSlots || [];
                        course.timeSlots.push({ day, period });
                        renderSchedule();
                    }
                }
            });
        }

        // 学生相关功能
        function addStudent() {
            if(!state.currentClass) return alert('请先选择班级');
            const name = document.getElementById('student-name').value;
            const gender = document.getElementById('student-gender').value;
            if(!name) return alert('请输入姓名');
            
            const student = {
                id: 's' + Date.now(),
                name,
                gender,
                seat: null
            };
            state.currentClass.students.push(student);
            document.getElementById('student-name').value = '';
            renderStudentPool();
        }

        function createStudentElement(student) {
            const div = document.createElement('div');
            div.className = `student-item ${student.gender === 'M' ? 'male' : 'female'}`;
            div.draggable = true;
            div.dataset.id = student.id;
            div.textContent = student.name;
            return div;
        }

        function renderStudentPool() {
            const pool = document.getElementById('student-pool');
            pool.innerHTML = '';
            state.currentClass?.students.forEach(student => {
                if(!student.seat) {
                    pool.appendChild(createStudentElement(student));
                }
            });
        }

        // 座位图功能
        function generateSeats() {
            if(!state.currentClass) return alert('请先选择班级');
            const rows = parseInt(document.getElementById('rows').value);
            const cols = parseInt(document.getElementById('cols').value);
            state.currentClass.seats = { rows, cols };
            
            const grid = document.getElementById('seat-map');
            grid.innerHTML = '';
            grid.style.gridTemplateColumns = `repeat(${cols}, 60px)`;
            
            for(let r=0; r<rows; r++) {
                for(let c=0; c<cols; c++) {
                    const cell = document.createElement('div');
                    cell.className = 'seat-cell';
                    cell.dataset.row = r;
                    cell.dataset.col = c;
                    
                    // 查找已分配座位的学生
                    const student = state.currentClass.students.find(s => 
                        s.seat?.row === r && s.seat?.col === c
                    );
                    if(student) {
                        cell.appendChild(createStudentElement(student));
                    }
                    
                    grid.appendChild(cell);
                }
            }
        }

        // 课程表功能
        function generateTimeSlots() {
            const tbody = document.getElementById('schedule-table').querySelector('tbody');
            tbody.innerHTML = '';
            state.timeSlots.forEach((slot, period) => {
                const tr = document.createElement('tr');
                let td = document.createElement('td');
                td.innerHTML = slot.label;
                tr.appendChild(td);
                
                for(let day=1; day<=7; day++) {
                    td = document.createElement('td');
                    td.className = 'schedule-cell';
                    td.dataset.day = day;
                    td.dataset.period = period;
                    tr.appendChild(td);
                }
                tbody.appendChild(tr);
            });
        }

        function addCourse() {
            const name = document.getElementById('course-name').value;
            const color = document.getElementById('course-color').value;
            if(!name) return alert('请输入课程名称');
            
            state.courses.push({
                id: 'c' + Date.now(),
                name,
                color,
                timeSlots: []
            });
            document.getElementById('course-name').value = '';
            renderCourses();
        }

        function renderCourses() {
            const pool = document.getElementById('student-pool');
            const coursesHTML = state.courses.map(course => `
                <div class="course-block" style="background:${course.color}" 
                     draggable="true" data-id="${course.id}">
                    ${course.name}
                </div>
            `).join('');
            pool.insertAdjacentHTML('afterbegin', coursesHTML);
        }

        function renderSchedule() {
            // 清空现有课程
            document.querySelectorAll('.course-block').forEach(el => el.remove());
            
            state.courses.forEach(course => {
                course.timeSlots.forEach(slot => {
                    const cell = document.querySelector(
                        `.schedule-cell[data-day="${slot.day}"][data-period="${slot.period}"]`
                    );
                    if(cell) {
                        const block = document.createElement('div');
                        block.className = 'course-block';
                        block.style.background = course.color;
                        block.draggable = true;
                        block.dataset.id = course.id;
                        block.textContent = course.name;
                        cell.appendChild(block);
                    }
                });
            });
        }

        // 班级管理
        function addClass() {
            const name = prompt('输入班级名称:');
            if(name) {
                const id = 'c' + Date.now();
                state.classes[id] = {
                    id,
                    name,
                    students: [],
                    seats: { rows: 6, cols: 8 }
                };
                updateClassSelect();
            }
        }

        function updateClassSelect() {
            const select = document.getElementById('class-select');
            select.innerHTML = '<option value="">选择班级...</option>';
            Object.values(state.classes).forEach(cls => {
                const option = document.createElement('option');
                option.value = cls.id;
                option.textContent = cls.name;
                select.appendChild(option);
            });
        }

        // 数据持久化
        function saveData() {
            localStorage.setItem('classManager', JSON.stringify(state));
            alert('数据已保存');
        }

        function loadState() {
            const saved = localStorage.getItem('classManager');
            if(saved) state = JSON.parse(saved);
            updateClassSelect();
            if(state.currentClass) {
                document.getElementById('class-select').value = state.currentClass.id;
            }
        }

        function resetData() {
            if(confirm('确定要重置当前数据吗?')) {
                state.currentClass = null;
                state.courses = [];
                renderStudentPool();
                generateSeats();
                renderSchedule();
            }
        }

        function exportData() {
            const blob = new Blob([JSON.stringify(state, null, 2)], {type: 'application/json'});
            const a = document.createElement('a');
            a.href = URL.createObjectURL(blob);
            a.download = '班级数据.json';
            a.click();
        }

        // 通用功能
        function showTab(tab) {
            document.querySelectorAll('.tab-content').forEach(t => t.style.display = 'none');
            document.getElementById(`${tab}-tab`).style.display = 'block';
        }

        // 事件监听
        document.getElementById('class-select').addEventListener('change', e => {
            const id = e.target.value;
            state.currentClass = id ? state.classes[id] : null;
            renderStudentPool();
            generateSeats();
            renderSchedule();
        });
    </script>
</body>
</html>